Ext.require([
    'Ext.data.*',
    'Ext.grid.*'
]);

Ext.onReady(function(){

	Ext.regModel('Photo', {
		fields: [
			{name: 'idPhoto', type: 'int'},
			{name: 'path', type: 'string'}
		]
	});

	function getExtraParams(){
		var s = document.location.search.split('?');
		var a = {};
		if(s.length > 1){
			a = Ext.urlDecode(s[1]);
		}
		var b = {
				memberEmail: Ext.util.Cookies.get('memberEmail'),
				memberPassword: Ext.util.Cookies.get('memberPassword')

		};

		return Ext.merge(a,b);
		
	};

    // create the Data Store
    var store = Ext.create('Ext.data.Store', {
        model: 'Photo',
        autoLoad: true,
        proxy: {
            type: 'ajax',
            url: '../../../cattolica-web/item/photo/list',
            reader: {
                type: 'json',
                idProperty: 'idPhoto',
				root: 'photos'
            },
			extraParams: getExtraParams(),
        }
    });

    // create the grid
    var grid = new Ext.grid.GridPanel({
        store: store,
        headers: [
			{text: 'Id', flex: 1, dataIndex: 'idPhoto', type: 'int', sortable: true, width: 20},
			{text: 'Path', dataIndex: 'path',  type: 'string', sortable: true, width: 330},

			{
                xtype: 'actionheader',
                width: 50,
                items: [{
                    icon   : '../../shared/icons/fam/book.png',  // Use a URL in the icon config
                    tooltip: 'View Photo',
                    handler: function(grid, rowIndex, colIndex) {
						var rec = store.getAt(rowIndex);
						document.location = '../../..' + rec.get('path');
                    }
                }, {
                    icon   : '../../shared/icons/fam/delete.gif',  // Use a URL in the icon config
                    tooltip: 'Eliminare',
                    handler: function(grid, rowIndex, colIndex) {
						var rec = store.getAt(rowIndex);
						var idPhoto = rec.get('idPhoto');
						Ext.Ajax.request({
							url: '../../../cattolica-web/item/photo/remove',
							params: Ext.merge(getExtraParams(), {idPhoto: idPhoto}),
							success: function(response){
								store.load();
							},
							failure: function(response) {
								Ext.Msg.alert('Failed', response.statusText);
							}
						});
                    }

                }]
            }

        ],
        width: 400,
        height: 200,
		iconCls: 'icon-grid',

        // inline toolbars
        tbar:[{
            text:'Upload di file',
            tooltip:'Upload di file',
            iconCls: 'icon-add',
			handler : function() {
				document.location = 'add.html' + document.location.search;
			}
        }]
       

    });

	grid.render('div_main');

});